package com.hb.trade.api.routine.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hb.core.pojo.Attachments;
import com.hb.core.pojo.enums.ProjectTypeEnum;
import com.hb.core.pojo.project.file.dto.BidFileInfoDTO;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.model.constant.CommonConstant;
import org.fzzn.core.util.Enums;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @author jinhaolin
 * @date 2022/5/20 0020 14:56
 **/
@Slf4j
public class TenderFileCreateXmlUtil {

    public static File createZbInfoXml(BidSectionDTO bidSectionDTO, BidFileInfoDTO bidFileInfoDTO, String fileId) {
        try {
            // 创建解析器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            Document document = db.newDocument();

            // 创建节点
            document.setXmlStandalone(true);
            Element zbInfoXml = document.createElement("ZBInfoXml");
            Element zbInfo = document.createElement("ZBInfo");
            Element tenderProjectName = document.createElement("tenderProjectName");
            Element tenderCode = document.createElement("tenderCode");
            Element fileType = document.createElement("fileType");
            Element twoEnvelopeIf = document.createElement("twoEnvelopeIf");
            Element evaluationMethod = document.createElement("evaluationMethod");
            Element bidCode = document.createElement("bidCode");
            Element bidSectionName = document.createElement("bidSectionName");
            Element tenderProjectType = document.createElement("tenderProjectType");
            Element zbwjName = document.createElement("zbwjName");
            Element gcqdName = document.createElement("gcqdName");
            Element zbwjQZName = document.createElement("zbwjQZName");
            Element bidId = document.createElement("bidId");
            // 项目名称
            tenderProjectName.setTextContent(bidSectionDTO.getProjectName());
            zbInfo.appendChild(tenderProjectName);
            // 项目编码
            tenderCode.setTextContent(bidSectionDTO.getProjectCode());
            zbInfo.appendChild(tenderCode);
            // TODO 待确定文件类型
            fileType.setTextContent("");
            zbInfo.appendChild(fileType);
            // 是否两阶段
            if (bidSectionDTO.getTwoStageFlag() != null) {
                twoEnvelopeIf.setTextContent(bidSectionDTO.getTwoStageFlag().toString());
            }
            zbInfo.appendChild(twoEnvelopeIf);
            // TODO 待确定评标办法字段
            evaluationMethod.setTextContent("");
            zbInfo.appendChild(evaluationMethod);
            // 标段编码
            bidCode.setTextContent(bidSectionDTO.getSectionCode());
            zbInfo.appendChild(bidCode);
            // 标段名称
            bidSectionName.setTextContent(bidSectionDTO.getSectionName());
            zbInfo.appendChild(bidSectionName);
            //项目类型
            ProjectTypeEnum projectEnum = Enums.of(ProjectTypeEnum.class, bidSectionDTO.getProjectType());
            tenderProjectType.setTextContent(projectEnum.getShowName());
            zbInfo.appendChild(tenderProjectType);
            if (bidFileInfoDTO != null) {
                // 招标文件--未签章
                Attachments bidFile = bidFileInfoDTO.getBiddingDocumentPdf();
                if (CollectionUtil.isNotEmpty(bidFile)) {
                    zbwjName.setTextContent(bidFile.get(0).getRawFileName());
                } else {
                    zbwjName.setTextContent("");
                }
                // 工程量清单
                Attachments drawingFile = bidFileInfoDTO.getDrawing();
                if (CollectionUtil.isNotEmpty(drawingFile)) {
                    gcqdName.setTextContent(drawingFile.get(0).getRawFileName());
                } else {
                    gcqdName.setTextContent("");
                }
                // 招标文件---签章
                Attachments signUpFile = bidFileInfoDTO.getBiddingDocumentSignaturePdf();
                if (CollectionUtil.isNotEmpty(signUpFile)) {
                    zbwjQZName.setTextContent(signUpFile.get(0).getRawFileName());
                } else {
                    zbwjQZName.setTextContent("");
                }
            }

            zbInfo.appendChild(zbwjName);
            zbInfo.appendChild(gcqdName);
            zbInfo.appendChild(zbwjQZName);
            // 标段id
            if (bidSectionDTO.getId() != null) {
                bidId.setTextContent(bidSectionDTO.getId().toString());
            }
            zbInfo.appendChild(bidId);

            zbInfoXml.appendChild(zbInfo);

            document.appendChild(zbInfoXml);

            // 创建TransformerFactory对象
            TransformerFactory tff = TransformerFactory.newInstance();
            // 创建 Transformer对象
            Transformer tf = tff.newTransformer();
            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            File file = new File(CommonConstant.TEMP_PATH + "/" + fileId + "/" + "zbInfoxml.xml");
            FileUtil.writeBytes("".getBytes(StandardCharsets.UTF_8),file);
            // 创建xml文件并写入内容
            tf.transform(new DOMSource(document), new StreamResult(file));
            log.debug("生成zbInfoxml.xml成功");
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成zbInfoxml.xml失败");
        }
        return null;
    }

    public static File createKBYLBXml(String openingSchedulerContent, String fileId) {
        try {
            // 创建解析器工厂
            JSONArray jsonArray = JSONUtil.parseArray(openingSchedulerContent);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            Document document = db.newDocument();

            // 创建节点
            document.setXmlStandalone(true);
            Element kbylXml = document.createElement("KBYLXml");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String bidOpeningName = jsonObject.getStr("bidOpeningName");
                String content = jsonObject.getStr("content");
                Integer fillType = jsonObject.getInt("fillType");
                Element para = document.createElement("Para" + i);
                para.setTextContent(bidOpeningName);
                para.setAttribute("content", content);
                para.setAttribute("dataType", fillType.toString());
                para.setAttribute("xmlns", bidOpeningName);
                kbylXml.appendChild(para);

            }
            document.appendChild(kbylXml);

            // 创建TransformerFactory对象
            TransformerFactory tff = TransformerFactory.newInstance();
            // 创建 Transformer对象
            Transformer tf = tff.newTransformer();
            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            File file = new File(CommonConstant.TEMP_PATH + "/" + fileId + "/" + "fileKBYLxml.xml");
            FileUtil.writeBytes("".getBytes(StandardCharsets.UTF_8),file);
            // 创建xml文件并写入内容
            tf.transform(new DOMSource(document), new StreamResult(file));
            log.debug("生成fileKBYLxml.xml成功");
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成fileKBYLxml.xml失败");
        }
        return null;
    }

    public static File createFileGuidXml(String guid, String fileId) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            Document document = db.newDocument();

            // 创建节点
            document.setXmlStandalone(true);
            Element guidElement = document.createElement("Guid");
            guidElement.setTextContent(guid);

            document.appendChild(guidElement);
            // 创建TransformerFactory对象
            TransformerFactory tff = TransformerFactory.newInstance();
            // 创建 Transformer对象
            Transformer tf = tff.newTransformer();
            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            File file = new File(CommonConstant.TEMP_PATH + "/" + fileId + "/" + "fileGuid.xml");
            FileUtil.writeBytes("".getBytes(StandardCharsets.UTF_8),file);
            // 创建xml文件并写入内容
            tf.transform(new DOMSource(document), new StreamResult(file));
            log.debug("生成fileGuid.xml成功");
            return file;

        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成fileGuid.xml失败");
        }
        return null;
    }

    public static File createTbInfo(String fileId) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            Document document = db.newDocument();

            // 创建节点
            document.setXmlStandalone(true);
            Element tbinfoElement = document.createElement("tbinfoxml");
            Element lhtElement = document.createElement("isLht");
            lhtElement.setTextContent("0");
            tbinfoElement.appendChild(lhtElement);

            document.appendChild(tbinfoElement);
            // 创建TransformerFactory对象
            TransformerFactory tff = TransformerFactory.newInstance();
            // 创建 Transformer对象
            Transformer tf = tff.newTransformer();
            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            File file = new File(CommonConstant.TEMP_PATH + "/" + fileId + "/" + "tbinfo.xml");
            FileUtil.writeBytes("".getBytes(StandardCharsets.UTF_8),file);
            // 创建xml文件并写入内容
            tf.transform(new DOMSource(document), new StreamResult(file));
            log.debug("生成tbinfo.xml成功");
            return file;

        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成tbinfo.xml失败");
        }
        return null;
    }

    public static File createDigitalEnvelopeXml(String sectionId, String digitalEnvelope, String fileId) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            Document document = db.newDocument();

            // 创建节点
            document.setXmlStandalone(true);
            Element message = document.createElement("Message");
            Element digitalEnvelopeNode = document.createElement("digitalEnvelope");
            Element bidId = document.createElement("bidId");
//            Element mac = document.createElement("mac");
            Element version = document.createElement("version");

            digitalEnvelopeNode.setTextContent(digitalEnvelope);
            message.appendChild(digitalEnvelopeNode);

            bidId.setTextContent(sectionId);
            message.appendChild(bidId);

//            mac.setTextContent("");
//            message.appendChild(mac);

            version.setTextContent("1.5.0.0");
            message.appendChild(version);

            document.appendChild(message);
            // 创建TransformerFactory对象
            TransformerFactory tff = TransformerFactory.newInstance();
            // 创建 Transformer对象
            Transformer tf = tff.newTransformer();
            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            File file = new File(CommonConstant.TEMP_PATH + "/" + fileId + "/" + "digitalEnvelopexml.xml");
            FileUtil.writeBytes("".getBytes(StandardCharsets.UTF_8),file);
            // 创建xml文件并写入内容
            tf.transform(new DOMSource(document), new StreamResult(file));
            log.debug("生成digitalEnvelope.xml成功");
            return file;

        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成digitalEnvelope.xml失败");
        }
        return null;
    }


}
